package com.cn.qgx428.orderingmeal.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.qgx428.orderingmeal.R;
import com.cn.qgx428.orderingmeal.Store;
import com.cn.qgx428.orderingmeal.animation.FoodToCar;
import com.cn.qgx428.orderingmeal.dialog.FoodSMInfo;
import com.cn.qgx428.orderingmeal.myClass.Car;
import com.cn.qgx428.orderingmeal.myClass.CollectionFood;
import com.cn.qgx428.orderingmeal.myClass.CollectionShop;
import com.cn.qgx428.orderingmeal.myClass.Food;
import com.cn.qgx428.orderingmeal.myClass.MyKeyInfo;
import com.cn.qgx428.orderingmeal.myClass.Shop;
import com.cn.qgx428.orderingmeal.myClass.User;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SQLQueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by QinX on 2017/4/5.
 */

public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {

    private static final String TAG = "FoodAdapter";

    private Context context;
    private List<Food> foods;

    private MyKeyInfo keyInfo;

    private Activity activity;

    private static final int GET_START_LOCATION = 0;
    private static final int GET_END_LOCATION = 1;


    public FoodAdapter(Context context, List<Food>foods, MyKeyInfo keyInfo, Activity activity){
        this.context=context;
        this.foods=foods;
        this.keyInfo = keyInfo;
        this.activity = activity;
    }


    @Override
    public FoodViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.store_food_item, parent, false);
        FoodViewHolder foodViewHolder = new FoodViewHolder(itemView);
        return foodViewHolder;
    }

    @Override
    public void onBindViewHolder(final FoodViewHolder holder, final int position) {
        //根据名单改变食物按钮
        BmobQuery<CollectionFood> eq1 = new BmobQuery<CollectionFood>();
        Shop sqlShop = new Shop();
        sqlShop.setObjectId(keyInfo.getNowShopID());
        eq1.addWhereEqualTo("shop",sqlShop);
        BmobQuery<CollectionFood> eq2 = new BmobQuery<CollectionFood>();
        User sqlUser = new User();
        sqlUser.setObjectId(keyInfo.getUserID());
        eq2.addWhereEqualTo("user",sqlUser);
        BmobQuery<CollectionFood> eq3 = new BmobQuery<CollectionFood>();
        Food sqlFood = new Food();
        sqlFood.setObjectId(foods.get(position).getObjectId());
        eq3.addWhereEqualTo("food",sqlFood);
        List<BmobQuery<CollectionFood>> andQuerys = new ArrayList<BmobQuery<CollectionFood>>();
        andQuerys.add(eq1);
        andQuerys.add(eq2);
        andQuerys.add(eq3);
        BmobQuery<CollectionFood> queryAnd = new BmobQuery<CollectionFood>();
        queryAnd.and(andQuerys);
        queryAnd.findObjects(new FindListener<CollectionFood>() {
            @Override
            public void done(List<CollectionFood> list, BmobException e) {
                if (e == null){
                    if (list.size() > 0){
                        holder.collectionFoodDataID = list.get(0).getObjectId();
                        holder.foodCollectionImg.setImageResource(R.drawable.store_collection1);
                        holder.collectFood = holder.COLLECTION_FOOD;
                    }
                }else{
                    Log.d(TAG, "搜查食物收藏表: "+e.getErrorCode()+e.getMessage());
                }
            }
        });


        holder.foodName.setText(foods.get(position).getName());
        holder.foodPrice.setText(foods.get(position).getPrice().toString());
        Picasso.with(context).load(foods.get(position).getPic().getFileUrl()).fit().into(holder.foodPic);
        holder.foodCollectionBtnLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CollectionFood collectionFood = new CollectionFood();
                Food food = new Food();
                food.setObjectId(foods.get(position).getObjectId());
                User user = new User();
                user.setObjectId(keyInfo.getUserID());
                Shop shop = new Shop();
                shop.setObjectId(keyInfo.getNowShopID());
                collectionFood.setUser(user);
                collectionFood.setShop(shop);
                collectionFood.setFood(food);
                if (holder.collectFood == holder.NOT_COLLECTION_FOOD){
                    collectionFood.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null){
                                holder.collectionFoodDataID = s;
                                holder.foodCollectionImg.setImageResource(R.drawable.store_collection1);
                                holder.collectFood = holder.COLLECTION_FOOD;
                                Toast.makeText(context, "收藏菜品", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                                Log.d(TAG, "收藏食物"+e.getErrorCode()+e.getMessage());
                            }
                        }
                    });
                } else if(holder.collectFood == holder.COLLECTION_FOOD){
                    collectionFood.setObjectId(holder.collectionFoodDataID);
                    collectionFood.delete(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null){
                                holder.foodCollectionImg.setImageResource(R.drawable.store_collection);
                                holder.collectFood = holder.NOT_COLLECTION_FOOD;
                                Toast.makeText(context, "取消收藏", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                                Log.d(TAG, "取消收藏食物: "+e.getErrorCode()+e.getMessage());
                            }
                        }
                    });
                }
            }
        });

        //食物提交框逻辑事件
        holder.foodOrderBtnLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyInfo.setNowFoodID(foods.get(position).getObjectId());
                keyInfo.setNowFoodName(foods.get(position).getName());
                final FoodSMInfo foodSMInfo = new FoodSMInfo(context, keyInfo);
                foodSMInfo.setSubmit(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d(TAG, "在Food适配器获取食物数量：" + foodSMInfo.getFoodNumber());
                        String foodID = foods.get(position).getObjectId();
                        String userID = keyInfo.getUserID();
                        int foodAmount = foodSMInfo.getFoodNumber();
                        submitFoodTOCar(userID, foodID, foodAmount);
                        foodSMInfo.dismiss();
                        FoodToCar buyFoodAnimation = new FoodToCar(activity);
                        int[] to_location = getStartLocation(GET_END_LOCATION);
                        int[] from_location = getStartLocation(GET_START_LOCATION);
                        buyFoodAnimation.startAnim(from_location,to_location);
                    }
                });
                foodSMInfo.show();
            }
        });
    }

    /**
     * @param userID
     * @param foodID
     * @param foodAmount
     * @return
     *将食物提交到购物车
     */
    private void submitFoodTOCar(String userID, String foodID, final Integer foodAmount) {
        final Car car = new Car();
        Food food = new Food();
        food.setObjectId(foodID);
        car.setFood(food);
        car.setUserID(userID);
        car.setAmount(foodAmount);

        //查询用户是否添加过此食物，若添加过则添加数量，否则插入新数据
        BmobQuery<Car> query = new BmobQuery<Car>();
        query.addWhereEqualTo("food",new BmobPointer(food));
        BmobQuery<Car> query2 = new BmobQuery<Car>();
        query2.addWhereEqualTo("userID",userID);
        List<BmobQuery<Car>> qs = new ArrayList<BmobQuery<Car>>();
        qs.add(query);
        qs.add(query2);
        BmobQuery<Car> q = new BmobQuery<Car>();
        q.and(qs);
        q.findObjects(new FindListener<Car>() {
            @Override
            public void done(List<Car> list, BmobException e) {
                if (e == null){
                    if (list.size() == 0){
                        //购物车无记录，添加新数据
                        car.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if (e == null){
                                    Log.d(TAG, "添加数据到购物车 "+s);
                                } else {
                                    Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                                    Log.d(TAG, "添加数据到购物车 "+e.getErrorCode()+e.getMessage());
                                }
                            }
                        });
                    } else{
                        //购物车有记录，更改数据
                        car.setObjectId(list.get(0).getObjectId());
                        car.setAmount(list.get(0).getAmount());
                        car.increment("amount",foodAmount);
                        car.update(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null){
                                    Log.d(TAG, "更新购物车数据 ");
                                } else{
                                    Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                                    Log.d(TAG, "更新购物车数据 "+e.getErrorCode()+e.getMessage());
                                }
                            }
                        });
                    }
                } else{
                    Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "查询用户是否添加过食物 :" +e.getErrorCode()+ e.getMessage());
                }
            }
        });

    }

    private int[] getStartLocation(int way){
        int[] location = new int[2];
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        if (way == GET_START_LOCATION){
            location[0] = dm.widthPixels /2 ;
            location[1] = dm.heightPixels/2 + dm.heightPixels/15;
        } else if(way == GET_END_LOCATION){
            location[0] = 0;
            location[1] = dm.heightPixels/2 - dm.heightPixels/4;
        }
        return location;
    }

    @Override
    public int getItemCount() {
        return foods.size();
    }

    public class FoodViewHolder extends RecyclerView.ViewHolder{

        private TextView foodName;
        private TextView foodPrice;
        private ImageView foodPic;

        private LinearLayout foodCollectionBtnLayout;
        private LinearLayout foodOrderBtnLayout;
        private ImageView foodCollectionImg;

        private int COLLECTION_FOOD = 1;
        private int NOT_COLLECTION_FOOD = 0;
        private int collectFood = NOT_COLLECTION_FOOD;

        private String collectionFoodDataID;


        public FoodViewHolder(View itemView) {
            super(itemView);
            foodName = (TextView) itemView.findViewById(R.id.store_food_item_name);
            foodPrice = (TextView) itemView.findViewById(R.id.store_food_item_price);
            foodPic = (ImageView) itemView.findViewById(R.id.store_food_item_pic);
            foodCollectionBtnLayout =(LinearLayout) itemView.findViewById(R.id.store_food_item_colletionBtnLayout);
            foodOrderBtnLayout = (LinearLayout) itemView.findViewById(R.id.store_food_item_orderBtnLayout);
            foodCollectionImg = (ImageView) itemView.findViewById(R.id.store_food_item_colletionImg);
        }
    }


}
